package com.jeff.utils.concurrent;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * author：duff
 * version：1.0.0
 * date：2017/8/27
 * desc：单任务执行调度器
 */
public class SequenceTaskScheduler {

    private static Handler mHandler = new Handler(Looper.getMainLooper());
    // 构造单线程的线程池
    private static ExecutorService mExecutorService = Executors.newSingleThreadExecutor();

    public static void execute(Runnable runnable) {
        if (runnable != null) {
            mExecutorService.execute(runnable);
        }
    }

    public static <IN, OUT> void execute(Task<IN, OUT> task) {
        exec(task);
    }

    private static <IN, OUT> void exec(final Task<IN, OUT> task) {
        if (task != null) {
            mExecutorService.execute(new Runnable() {
                @Override
                public void run() {
                    final OUT output = task.onBackground(task.mInput);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            task.onForeground(output);
                        }
                    });
                }
            });
        }
    }

}
